/*
 *  ball.cpp
 *  fadeout_simulator
 *
 *  Created by 真鍋 大度 on 11/02/26.
 *  Copyright 2011 Rhizomatiks. All rights reserved.
 *
 */

#include "ball.h"
#include "ofxDaito.h"

void ball::setup(int _myID, vector<checkPoint*> & _checkPoints){
	checkPoints = _checkPoints;
	bAmIDead = false;
	w = 200;
	h = 16;
	ratio = 4;
	x = 0;
	y = 0;
	pos.set(0, 0);
	age	= 0;	
	myID = _myID;
	
//	currentColorImage.allocate(w, h);
}

void ball::update(unsigned char * _colorpixels){
//void ball::update(){	
	currentColorPixels = _colorpixels;
	x = age % w;
	y = age / w;
	checkPointID = y;
	int px = y%2==0 ? w - x - 1 : x;
	pos.x = px * ratio;		
	pos.y = y * ratio;
	col.r = currentColorPixels[(px + y * w) * 3 + 0];
	col.g = currentColorPixels[(px + y * w) * 3 + 1];
	col.b = currentColorPixels[(px + y * w) * 3 + 2];	
	speed = (ofRandom(100, 200) / 10.0) + 20.0;
}

void ball::updateWithAge(unsigned char * _colorpixels, int _myage){
	//void ball::update(){	
	age = _myage;
	currentColorPixels = _colorpixels;
	x = age % w;
	y = age / w;
	checkPointID = y;
	int px = y%2==0 ? w - x - 1 : x;
	pos.x = px * ratio;		
	pos.y = y * ratio;
	col.r = currentColorPixels[(px + y * w) * 3 + 0];
	col.g = currentColorPixels[(px + y * w) * 3 + 1];
	col.b = currentColorPixels[(px + y * w) * 3 + 2];	
	speed = (ofRandom(100, 200) / 10.0) + 20.0;
}
void ball::sendOSC(){
	int grey = (col.r + col.g + col.b) / 3.0f;			
	ofxDaito::bang("/vol", checkPointID, grey);
	
	if (grey>255) {
		ofxDaito::bang("/volpeak", checkPointID, grey);
	}	
	if (x==0 && bActive) {
		ofxDaito::bang("/pass", myID, y, speed);			
	}
}

void ball::sendCheckPoint(){
	if(x==0&&bActive){
		checkPoints[y]->passing(myID, speed);
	}
}

void ball::draw(){
	if(bActive){
		ofSetColor(col.r, col.g, col.b);	
		glPointSize(ratio);
		glBegin(GL_POINTS);
		glVertex3f(pos.x, pos.y, 0);
		glEnd();
	}
	
}

void ball::incrementAge(){
	if (bActive) {
		age++;
		if (age > w * h - 1)
		{
//			inactivate
			age = 0;
//			bAmIDead = true;
		}
	}
		
}

void ball::activate(){
	bActive = true;
}

void ball::inactivate(){
	age = 0;
	bActive = false;
}

